import cv2
import numpy as np
import os

# 读取图片
image = cv2.imread("/Users/champ/Documents/知识库-Lexar/自媒体/24-11-27 科普视频/硬件/家电-removebg-preview.png")  # 替换为你的图片路径

# 转换为灰度图
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 阈值处理，使图标与背景分离
_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)

# 查找轮廓
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# 创建保存图片的目录
if not os.path.exists("output_images"):
    os.makedirs("output_images")

# 遍历每个轮廓，裁剪并保存图标
for i, contour in enumerate(contours):
    x, y, w, h = cv2.boundingRect(contour)
    icon = image[y:y + h, x:x + w]
    cv2.imwrite(os.path.join("output_images", f"icon_{i}.png"), icon)